package com.itzzj.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.itzzj.common.anno.Sensitive;
import com.itzzj.common.strategy.SensitiveStrategy;

import java.io.IOException;
import java.util.Objects;

/**
 * 序列化注解自定义实现
 *
 */
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveStrategy strategy;

    /**
     * JsonSerializer<String>：指定String类型，serialize() 方法用于将修改后的数据载入
     * @param value
     * @param jsonGenerator
     * @param serializerProvider
     * @throws IOException
     */
    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(strategy.desensitizer().apply(value));
    }

    /**
     * 获取属性上的注解
     * @param prov
     * @param property
     * @return
     * @throws JsonMappingException
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Sensitive annotation = property.getAnnotation(Sensitive.class);
        if(Objects.nonNull(annotation) && Objects.equals(String.class,property.getType().getRawClass())){
            this.strategy = annotation.strategy();
            return this;
        }
        return prov.findValueSerializer(property.getType(),property);
    }
}
